package managers;

import android.content.Context;
import android.location.GpsStatus;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;

import java.lang.reflect.Field;
import java.security.Provider;
import java.util.HashMap;

/**
 * 移除多余的监听
 * Created by 凯 on 2015/12/15.
 */
public class LocationHelper {
    // 移除多余状态监听
    public static void removeAllStatusListen(LocationManager locationManager)
    {
        Class loc = LocationManager.class;
        Field f0;
        Field f1;

        try{
            f0 = loc.getDeclaredField("mGpsStatusListeners");
            f0.setAccessible(true);
            HashMap maps = (HashMap) f0.get(locationManager);
            for(Object o:maps.keySet())
            {
                locationManager.removeGpsStatusListener((GpsStatus.Listener) o);
            }

            f1 = loc.getDeclaredField("mListeners");
            f1.setAccessible(true);
            HashMap mps2 = (HashMap) f1.get(locationManager);
            for(Object o:mps2.keySet())
            {
                locationManager.removeUpdates((LocationListener) o);
            }

        }catch (Exception e)
        {
            e.printStackTrace();
        }
    }


    // 一次获取经纬度

    /**
     *
     * @param uiHandler readable
     * @param context readable
     * @param runnable writable
     * @param jingwiedu writable
     */
    public static void getJINGWEIDU(final Handler uiHandler,Context context, final Runnable runnable, final double[] jingwiedu)
    {

        final LocationManager locationManager = (LocationManager)context.getSystemService(Context.LOCATION_SERVICE);
        LocationListener locationListener = new LocationListener() {
            @Override
            public void onLocationChanged(Location location) {
                jingwiedu[0] = location.getLongitude();
                jingwiedu[1] = location.getLatitude();

                locationManager.removeUpdates(this);
                uiHandler.post(runnable);
            }

            @Override
            public void onStatusChanged(String provider, int status, Bundle extras) {

            }

            @Override
            public void onProviderEnabled(String provider) {

            }

            @Override
            public void onProviderDisabled(String provider) {

            }
        };

        locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,0,0,locationListener);


    }
}
